package com.gloaba.common.security.feign;



import com.gloaba.common.core.constant.SecurityConstants;
import com.gloaba.common.core.utils.IpUtils;
import com.gloaba.common.core.utils.ServletUtils;
import com.gloaba.common.core.utils.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * feign 请求拦截器
 *
 * @author Zane
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor
{
    @Override
    public void apply(RequestTemplate requestTemplate)
    {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        requestTemplate.header(SecurityConstants.FROM_SOURCE, SecurityConstants.INNER);
        // 配置客户端IP
        requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr(ServletUtils.getRequest()));

        if (Objects.nonNull(httpServletRequest))
        {
            Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
            // 传递用户信息请求头，防止丢失
            String clientType = headers.get(SecurityConstants.REQUEST_HEADER_CLIENT_TYPE);
            if (StringUtils.isNotEmpty(clientType))
            {
                requestTemplate.header(SecurityConstants.REQUEST_HEADER_CLIENT_TYPE, clientType);
            }
            String token = headers.get(SecurityConstants.TOKEN_AUTHENTICATION);
            if (StringUtils.isNotEmpty(token))
            {
                requestTemplate.header(SecurityConstants.TOKEN_AUTHENTICATION, token);
            }
        }
    }
}
